<template>
  <div class="server-main">
    <el-form :inline="true" v-model="modelData" class="search-form">
      <el-form-item label="任务名称:" class="form-input">
        <el-input v-model.trim="modelData.taskName" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态:" class="form-input">
        <el-select v-model="modelData.status">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="编辑中" :value="0"></el-option>
          <el-option label="启用" :value="1"></el-option>
          <el-option label="停用" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button id="btn" type="primary" size="small" @click="onSubmit(1)"
          >查询</el-button
        >
      </el-form-item>
    </el-form>

    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">采集任务管理</span>
        <div>
          <el-button type="primary" size="small" @click="openCreateTask"
            >创建任务</el-button
          >
          <!-- <el-button type="primary" size="small" @click="execAllTask"
            >立即执行</el-button
          > -->
        </div>
      </div>
      <el-table
        :data="tableList"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
        @row-click="updateCurrentItem"
      >
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center"
          fixed="left"
        ></el-table-column>
        <el-table-column
          prop="taskName"
          label="任务名称"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="syncDataSource"
          label="同步数据源"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="syncObject"
          label="同步对象"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column
          prop="targetDataSource"
          label="目标数据源"
          align="center"
          show-overflow-tooltip
        ></el-table-column> -->
        <el-table-column
          prop="targetModel"
          label="目标模型"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="schedulingFrequency"
          label="调度类型/频率"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="lastExcuteTime"
          label="最近执行时间"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="status"
          label="调度状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <i
              class="little-circle"
              :class="status.get(+scope.row.status).className"
            ></i>
            <span>{{ status.get(+scope.row.status).name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="250">
          <template slot-scope="scope" class="test">
            <el-link
              v-for="item in status.get(+scope.row.status).operation"
              :key="item.name"
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="dynamicFunc(item.funcName, scope.row)"
              >{{ item.name }}</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="modelData.pageSize"
        :pager-count="7"
        :current-page="modelData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible1"
      @close="afterDialogClose()"
    >
      <el-form
        :model="modelParams"
        :rules="rules"
        ref="dialogForm1"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="任务名称:" prop="taskName" class="dialog-inline">
          <el-input
            maxlength="50"
            show-word-limit
            v-model.trim="modelParams.taskName"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="任务说明:"
          prop="description"
          class="dialog-inline"
        >
          <el-input
            type="textarea"
            v-model.trim="modelParams.description"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="创建人:" prop="createUserName"></el-form-item>
        <el-form-item label="创建时间:" prop="createTime"></el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm1" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <config-box
      :dialogFormVisible="dialogFormVisible2"
      :currentItem="currentItem"
      @closeConfigBox="closeConfigBox"
    ></config-box>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import moment from "moment";
import ConfigBox from "./configBox.vue";
export default {
  name: "DataCollectionTask",
  components: { ConfigBox },
  data: () => {
    return {
      dialogTitle: "创建任务",
      modelData: {
        taskName: "", // 任务名称
        status: -1, // 状态 1 启用，2禁用，-1全部， 0 编辑中
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      tableList: [], // 采集任务列表
      currentItem: {},
      status: new Map([
        [
          0,
          {
            className: "blue",
            name: "编辑中",
            operation: [
              {
                name: "编辑",
                funcName: "editTask",
              },
              {
                name: "配置",
                funcName: "configTask",
              },
              {
                name: "删除",
                funcName: "deleteTask",
              },
              {
                name: "启用",
                funcName: "enableTask",
              },
            ],
          },
        ],
        [
          1,
          {
            className: "green",
            name: "启用",
            operation: [
              {
                name: "配置",
                funcName: "configTask",
              },
              {
                name: "停用",
                funcName: "disableTask",
              },
              {
                name: "立即执行",
                funcName: "execTask",
              },
            ],
          },
        ],
        [
          2,
          {
            className: "red",
            name: "禁用",
            operation: [
              {
                name: "配置",
                funcName: "configTask",
              },
              {
                name: "启用",
                funcName: "enableTask",
              },
            ],
          },
        ],
      ]),
      total: 0, // 数据总条数
      loading: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      modelParams: {
        id: null,
        taskName: "", // 任务名称
        description: "", // 任务说明
        createTime: null, // 创建任务时间
      },
      rules: {
        taskName: [
          {
            required: true,
            message: "请输入任务名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getModelList();
  },
  computed: {
    ...mapState({
      containerDom: (state) => state.server.containerDom,
      conifgBoxIsOpen: (state) => state.dataCollection.conifgBoxIsOpen,
    }),
  },
  methods: {
    ...mapMutations({
      setTaskId: "dataCollection/setTaskId",
      setDataSourceId: "dataCollection/setDataSourceId",
      toggleConfigBoxDialog: "dataCollection/toggleConfigBoxDialog",
      toggleCurrentTab: "dataCollection/toggleCurrentTab",
    }),
    // 获取采集任务列表
    getModelList() {
      const params = this.modelData;
      this.$axios
        .post(this.$api.dataCollection.getTaskList, params)
        .then((res) => {
          let data = res.data.data;
          this.tableList = data.list;
          this.total = +data.total;
          this.modelData.pageNum = +data.pageNum;
          this.$utils.backtop(this.containerDom);
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum;
      this.getModelList();
    },

    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page;
      this.getModelList();
    },

    // 修改每页条数
    handleSizeChange(e) {
      this.modelData.pageSize = e;
      this.getModelList();
    },

    // 修改状态
    changeStatus(params) {
      this.$axios
        .post(this.$api.dataCollection.changeStatus, params)
        .then((res) => {
          let { code, message } = res.data;
          if (code !== 200) {
            this.$message.warning(message);
          } else {
            this.$message.success("状态修改成功！");
            this.onSubmit();
          }
        });
    },

    // 模态框关闭后
    afterDialogClose() {
      this.$refs.dialogForm1.resetFields();
    },
    // 打开创建任务
    openCreateTask() {
      this.dialogTitle = "创建任务";
      let nowTime = moment(Date.now()).format("YYYY-MM-DD HH:MM:SS");
      this.modelParams.id = null;
      this.modelParams.taskName = "";
      this.modelParams.description = "";
      this.modelParams.createTime = nowTime;
      // console.log("modelParams", this.modelParams);
      this.dialogFormVisible1 = true;
    },
    dynamicFunc(funcName, row) {
      this[funcName](row);
    },
    // 打开编辑任务
    editTask(row) {
      this.dialogTitle = "编辑任务";
      let { createTime, id, taskName, description } = row;
      this.dialogFormVisible1 = true;
      this.modelParams.id = id;
      this.modelParams.taskName = taskName;
      this.modelParams.description = description;
      this.modelParams.createTime = createTime;
    },
    // 打开配置
    configTask(row) {
      this.dialogFormVisible2 = true;
      this.setTaskId(row.id);
      this.setDataSourceId(row.syncDataSourceId);
      this.toggleConfigBoxDialog(true);
      this.toggleCurrentTab(1);
    },
    // 删除任务
    deleteTask(row) {
      let params = { id: row.id };
      this.$axios
        .get(this.$api.dataCollection.deleteTask, { params })
        .then((res) => {
          let code = res.data.code;
          let message = res.data.message;
          if (code !== 200) {
            this.$message.warning(message);
          } else {
            this.$message.success("删除成功！");
            this.onSubmit();
          }
        });
    },
    // 执行任务
    execTask(row) {
      this.$axios
        .post(`${this.$api.dataCollection.execTask}?id=${row.id}`)
        .then((res) => {
          let code = res.data.code;
          let message = res.data.message;
          if (code !== 200) {
            this.$message.warning(message);
          } else {
            this.$message.success("任务开始执行，请到采集结果中查看执行结果！"); // 执行完毕后当前条数据的状态会发生变化
            this.onSubmit();
          }
        });
    },
    // 停用任务
    disableTask(row) {
      this.$confirm("是否停用当前任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = { id: row.id, status: 2 };
          this.changeStatus(params);
        })
        .catch();
    },
    // 启用任务
    enableTask(row) {
      let params = { id: row.id, status: 1 };
      this.changeStatus(params);
    },
    // 启用任务
    // 取消
    resetDialogForm() {
      this.dialogFormVisible1 = false;
      // this.dialogFormVisible2 = false;
    },
    // 创建/编辑任务 确定
    submitDialogForm1() {
      this.$refs.dialogForm1.validate((valid) => {
        if (valid) {
          this.updateTask();
        } else {
          return false;
        }
      });
    },

    // 创建/编辑任务接口调用
    updateTask() {
      this.loading = true;
      let params = this.modelParams;

      this.$axios
        .post(this.$api.dataCollection.editTask, params)
        .then((res) => {
          if (+res.data.code !== 200) {
            this.$message.warning(res.data.message);
            this.loading = false;
            return;
          }
          this.$message.success("操作成功！");
          this.loading = false;
          this.dialogFormVisible1 = false;
          this.onSubmit();
        })
        .catch((error) => {
          this.$message.warning("操作失败，请稍后重试！");
          this.dialogFormVisible1 = false;
          this.loading = false;
        });
    },
    // 立即执行 ////////////////////? 入参
    execAllTask() {
      // this.$axios.get(this.$api.dataCollection.execAllTask)
    },
    updateCurrentItem(row) {
      this.currentItem = row;
    },
    closeConfigBox() {
      this.toggleConfigBoxDialog(false);
    },
  },
  watch: {
    conifgBoxIsOpen: {
      handler: function (val) {
        this.dialogFormVisible2 = val;
        if (!val) {
          this.onSubmit();
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;

  .cate-head {
    display: flex;

    .cate-right {
      #btn {
        margin-right: -10px;
      }
    }
  }

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .el-select {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #e0e0e0;
    }
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .little-circle {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;

      position: relative;
      right: 4px;
      top: -2px;
      &.green {
        background: #55c898;
      }
      &.red {
        background: #ee5564;
      }
      &.blue {
        background: dodgerblue;
      }
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }

  /deep/ .el-dialog {
    width: 500px;
    border-radius: 5px;
  }

  .dialog-inline {
    /deep/ .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }
}
</style>
